/*
 * @Author: ZMN
 * @Date: 2022-04-08 17:28:46
 * @LastEditTime: 2022-05-07 10:12:55
 * @LastEditors: Lw
 * @Description:
 * @FilePath: /v3-admin/src/utils/index.ts
 */
// export { importMetaEnv } from './importMetaEnv'

import _ from "lodash"

/**
 * Generate a random uuid.
 */
export function uuid(len: number, radix: number) {
  const chars =
    '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')
  let uuid: Array<any> = []
  radix = radix || chars.length
  if (len) {
    // Compact form
    for (let i: number = 0; i < len; i++)
      uuid[i] = chars[0 | (Math.random() * radix)]
  } else {
    // rfc4122, version 4 form
    var r: number

    // rfc4122 requires these characters
    uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'
    uuid[14] = '4'

    // Fill in random data.  At i==19 set the high bits of clock sequence as
    // per rfc4122, sec. 4.1.5
    for (let i: number = 0; i < 36; i++) {
      if (!uuid[i]) {
        r = 0 | (Math.random() * 16)
        uuid[i] = chars[i == 19 ? (r & 0x3) | 0x8 : r]
      }
    }
  }
  return uuid.join('')
}

/**
 * 动态插入css
 */
export const loadStyle = (url: string) => {
  const link = document.createElement('link')
  link.type = 'text/css'
  link.rel = 'stylesheet'
  link.href = url
  const head = document.getElementsByTagName('head')[0]
  head.appendChild(link)
}

/**
 * 替换树形结构的字段
 * @param {Array} list 要替换的数据
 * @param {Record<string, string>} keyMap 替换的映射表<替换后字段, 替换前字段>
 * @param {Array} childrenKey 子列表字段，默认children
 */
export const transformField = (
  list: any[] = [],
  keyMap: Record<string, string>,
  childrenKey: string = 'children'
) => {
  return list.map(listItem => {
    const cloneListItem = Object.assign({}, listItem)
    const hasChildren =
      listItem[childrenKey] && listItem[childrenKey].length > 0

    Object.keys(keyMap).forEach(key => {
      listItem[key] = cloneListItem[keyMap[key]]

      if (!keyMap.hasOwnProperty(keyMap[key])) {
        delete listItem[keyMap[key]]
      }
    })

    if (hasChildren) {
      transformField(listItem[childrenKey], keyMap, childrenKey)
    }

    return listItem
  })
}

/**
 * 树形数据转换
 * @param {*} data
 * @param {*} id
 * @param {*} pid
 */
 export function treeDataTranslate (data, id = 'id', pid = 'parentId') {
  var res:any = []
  var temp = {}
  for (var i = 0; i < data.length; i++) {
    temp[data[i][id]] = data[i]
  }
  for (var k = 0; k < data.length; k++) {
    if (temp[data[k][pid]] && data[k][id] !== data[k][pid]) {
      if (!temp[data[k][pid]]['children']) {
        temp[data[k][pid]]['children'] = []
      }
      if (!temp[data[k][pid]]['_level']) {
        temp[data[k][pid]]['_level'] = 1
      }
      data[k]['_level'] = temp[data[k][pid]]._level + 1
      temp[data[k][pid]]['children'].push(data[k])
    } else {
      res.push(data[k])
    }
  }
  return res
}

/**
 * 平铺树形结构
 */
 export function TreeDataFlat (data, childrenKey = 'children') {
  let arr:any = []
  const flat = (fData) => {
    if (fData && fData.length > 0) {
      fData.map(item => {
        arr.push(item)
        flat(item[childrenKey])
      })
    }
  }
  flat(data)
  return arr;
}

/**
 * Lightens a 6 char HEX color according to the passed percentage
 * @param {string} color The color to change
 * @param {number} amount The amount to change the color by
 * @returns {string} The processed color represented as HEX
 */
function addLight(color: string, amount: number): string {
  const cc = parseInt(color, 16) + amount
  const c = cc > 255 ? 255 : cc
  return c.toString(16).length > 1 ? c.toString(16) : `0${c.toString(16)}`
}
export function lighten(color: string, amount: number) {
  color = color.indexOf('#') >= 0 ? color.substring(1, color.length) : color
  amount = Math.trunc((255 * amount) / 100)
  return `#${addLight(color.substring(0, 2), amount)}${addLight(
    color.substring(2, 4),
    amount
  )}${addLight(color.substring(4, 6), amount)}`
}


// 获取url中全部参数的对象
export function getUrlAllParams(){
  // 解决乱码问题
  var url = decodeURI(window.location.href)
  var res = {}
  var url_data = _.split(url, '?').length > 1 ? _.split(url, '?')[1] : null ;
  if (!url_data) return null
  var params_arr = _.split(url_data, '&')
  _.forEach(params_arr, function(item) {
         var key = _.split(item, '=')[0]
         var value = _.split(item, '=')[1]
         res[key] = value
  }); 
  return res
}


/**
 * 将对象添加当作参数拼接到URL上面
 * @param baseUrl 需要拼接的url
 * @param obj 参数对象
 * @returns {string} 拼接后的对象
 * 例子:
 *  let obj = {a: '3', b: '4'}
 *  setObjToUrlParams('www.baidu.com', obj)
 *  ==>www.baidu.com?a=3&b=4
 */
 export function setObjToUrlParams(baseUrl: string, obj: object): string {
  let parameters = '';
  let url = '';
  for (const key in obj) {
    parameters += key + '=' + encodeURIComponent(obj[key]) + '&';
  }
  parameters = parameters.replace(/&$/, '');
  if (/\?$/.test(baseUrl)) {
    url = baseUrl + parameters;
  } else {
    url = baseUrl.replace(/\/?$/, '?') + parameters;
  }
  return url;
}


/**
 * 对象赋值
 */
 export function ObjectAssign (objectTarget, objectOrigin) {
  Object.keys(objectTarget).forEach(key => {
    if (objectOrigin.hasOwnProperty(key)) {
      objectTarget[key] = objectOrigin[key]
    }
  })
}
/** 计算字符串宽度 */
export function getTextWidth(text, fontSize) {
  // 创建临时元素
  const _span = document.createElement('span')
  // 放入文本
  _span.innerText = text
  // 设置文字大小
  _span.style.fontSize = fontSize + 'px'
  // span元素转块级
  _span.style.position = 'absolute'
  // span放入body中
  document.body.appendChild(_span)
  // 获取span的宽度
  let width = _span.offsetWidth
  // 从body中删除该span
  document.body.removeChild(_span)
  // 返回span宽度
  return width
}